import config from './config.js';
import { getWxToken } from './utils.js';
var auth = require('./auth.js');

const token = getWxToken();

const request = (
  url = '',
  method = 'GET',
  data = {},
  header = {
    'content-type': 'application/json',
    Authorization: token ? 'Bearer ' + token : '',
  }
) => {
  return new Promise((resolve, reject) => {
    data['isFrom'] = 0;
    data['appNo'] = appNo;
    data['timestamp'] = auth.getTimestamp();
    const sign = auth.sign(appKey, args);
    data['sign'] = sign;
    uni.request({
      url: config.baseUrl + url,
      method: method,
      data: data,
      header: header,
      dataType: 'json',
      success: (res) => {
        if (
          (res.statusCode === 200 && res.data.code === 403) ||
          res.statusCode === 401
        ) {
          uni.removeStorageSync('token');
          uni.reLaunch({
            url: '/pages/login/index',
          });
          reject(res.data);
          return;
        }
        resolve(res.data);
      },
      fail: (err) => {
        requestFail(err);
        reject(err);
      },
    });
  });
};

// 连接失败处理函数
const requestFail = (res) => {
  if (
    res.errMsg.indexOf('time out') > -1 ||
    res.errMsg.indexOf('timeout') > -1
  ) {
    uni.showToast({
      title: '请求超时,请检查您的网络',
      icon: 'none',
      duration: 3000,
    });
  } else if (res.errMsg.indexOf('connect error') > -1) {
    uni.showToast({
      title: '当前网络不佳,请稍后重试',
      icon: 'none',
      duration: 3000,
    });
  } else {
    // uni.showToast({
    //   title: '请求异常,请稍后再试',
    //   icon: 'none',
    //   duration: 3000,
    // });
  }
};

export default request;
